// 管理后台JavaScript功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 初始化所有弹出框
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // 自动隐藏警告框
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert-dismissible');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);

    // 表格行选择功能
    const selectAllCheckbox = document.querySelector('#selectAll');
    const rowCheckboxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]');
    
    if (selectAllCheckbox && rowCheckboxes.length > 0) {
        selectAllCheckbox.addEventListener('change', function() {
            rowCheckboxes.forEach(function(checkbox) {
                checkbox.checked = this.checked;
            }, this);
            updateBulkActions();
        });
        
        rowCheckboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                updateSelectAllState();
                updateBulkActions();
            });
        });
    }

    // 批量操作按钮
    const bulkActions = document.querySelectorAll('[data-bulk-action]');
    bulkActions.forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const action = this.dataset.bulkAction;
            const selectedItems = getSelectedItems();
            
            if (selectedItems.length === 0) {
                showAlert('请先选择要操作的项目', 'warning');
                return;
            }
            
            if (confirm(`确定要对选中的 ${selectedItems.length} 个项目执行"${this.textContent.trim()}"操作吗？`)) {
                executeBulkAction(action, selectedItems);
            }
        });
    });

    // 确认删除对话框
    const deleteButtons = document.querySelectorAll('[data-delete-confirm]');
    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const message = this.dataset.deleteConfirm || '确定要删除这个项目吗？';
            if (confirm(message)) {
                const form = this.closest('form');
                if (form) {
                    form.submit();
                } else {
                    window.location.href = this.href;
                }
            }
        });
    });

    // 实时搜索功能
    const searchInput = document.querySelector('input[data-search]');
    if (searchInput) {
        const searchTarget = searchInput.dataset.search;
        const targetElements = document.querySelectorAll(searchTarget);
        
        searchInput.addEventListener('input', debounce(function() {
            const searchTerm = this.value.toLowerCase();
            
            targetElements.forEach(function(element) {
                const text = element.textContent.toLowerCase();
                const shouldShow = text.includes(searchTerm);
                element.style.display = shouldShow ? '' : 'none';
            });
        }, 300));
    }

    // 表单验证增强
    const forms = document.querySelectorAll('form[data-validate]');
    forms.forEach(function(form) {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
            }
        });
    });

    // 自动保存草稿
    const autoSaveForms = document.querySelectorAll('form[data-auto-save]');
    autoSaveForms.forEach(function(form) {
        const inputs = form.querySelectorAll('input, textarea, select');
        inputs.forEach(function(input) {
            input.addEventListener('input', debounce(function() {
                saveDraft(form);
            }, 2000));
        });
    });

    // 图片预览功能
    const imageInputs = document.querySelectorAll('input[type="file"][accept*="image"]');
    imageInputs.forEach(function(input) {
        input.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                previewImage(file, this);
            }
        });
    });

    // 代码编辑器（如果有）
    const codeEditors = document.querySelectorAll('textarea[data-editor]');
    codeEditors.forEach(function(textarea) {
        initCodeEditor(textarea);
    });
});

// 工具函数
function updateSelectAllState() {
    const selectAllCheckbox = document.querySelector('#selectAll');
    const rowCheckboxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]');
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]:checked');
    
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = checkedBoxes.length === rowCheckboxes.length;
        selectAllCheckbox.indeterminate = checkedBoxes.length > 0 && checkedBoxes.length < rowCheckboxes.length;
    }
}

function updateBulkActions() {
    const selectedItems = getSelectedItems();
    const bulkActionButtons = document.querySelectorAll('[data-bulk-action]');
    
    bulkActionButtons.forEach(function(button) {
        button.disabled = selectedItems.length === 0;
    });
}

function getSelectedItems() {
    const checkboxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]:checked');
    return Array.from(checkboxes).map(function(checkbox) {
        return checkbox.value;
    });
}

function executeBulkAction(action, selectedItems) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/admin/bulk-action/${action}`;
    
    selectedItems.forEach(function(itemId) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'selected_items';
        input.value = itemId;
        form.appendChild(input);
    });
    
    document.body.appendChild(form);
    form.submit();
}

function validateForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(function(field) {
        if (!field.value.trim()) {
            showFieldError(field, '此字段为必填项');
            isValid = false;
        } else {
            clearFieldError(field);
        }
    });
    
    // 邮箱验证
    const emailFields = form.querySelectorAll('input[type="email"]');
    emailFields.forEach(function(field) {
        if (field.value && !isValidEmail(field.value)) {
            showFieldError(field, '请输入有效的邮箱地址');
            isValid = false;
        }
    });
    
    // URL验证
    const urlFields = form.querySelectorAll('input[type="url"]');
    urlFields.forEach(function(field) {
        if (field.value && !isValidUrl(field.value)) {
            showFieldError(field, '请输入有效的URL地址');
            isValid = false;
        }
    });
    
    return isValid;
}

function showFieldError(field, message) {
    clearFieldError(field);
    
    field.classList.add('is-invalid');
    const errorDiv = document.createElement('div');
    errorDiv.className = 'invalid-feedback';
    errorDiv.textContent = message;
    field.parentElement.appendChild(errorDiv);
}

function clearFieldError(field) {
    field.classList.remove('is-invalid');
    const errorDiv = field.parentElement.querySelector('.invalid-feedback');
    if (errorDiv) {
        errorDiv.remove();
    }
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function isValidUrl(url) {
    try {
        new URL(url);
        return true;
    } catch {
        return false;
    }
}

function saveDraft(form) {
    const formData = new FormData(form);
    const data = {};
    
    for (let [key, value] of formData.entries()) {
        data[key] = value;
    }
    
    fetch('/admin/save-draft', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('草稿已自动保存', 'success');
        }
    })
    .catch(error => {
        console.error('保存草稿失败:', error);
    });
}

function previewImage(file, input) {
    const reader = new FileReader();
    reader.onload = function(e) {
        let preview = input.parentElement.querySelector('.image-preview');
        if (!preview) {
            preview = document.createElement('div');
            preview.className = 'image-preview mt-2';
            input.parentElement.appendChild(preview);
        }
        
        preview.innerHTML = `
            <img src="${e.target.result}" class="img-thumbnail" style="max-width: 200px; max-height: 200px;">
            <div class="mt-2">
                <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeImagePreview(this)">
                    <i class="fas fa-times"></i> 移除
                </button>
            </div>
        `;
    };
    reader.readAsDataURL(file);
}

function removeImagePreview(button) {
    const preview = button.closest('.image-preview');
    const input = preview.parentElement.querySelector('input[type="file"]');
    
    preview.remove();
    input.value = '';
}

function initCodeEditor(textarea) {
    // 这里可以集成代码编辑器，如 CodeMirror 或 Monaco Editor
    textarea.style.fontFamily = 'Monaco, Consolas, "Courier New", monospace';
    textarea.style.fontSize = '14px';
    textarea.style.lineHeight = '1.5';
}

function showAlert(message, type = 'info') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container-fluid main .row') || document.querySelector('main');
    container.insertBefore(alertDiv, container.firstChild);
    
    setTimeout(function() {
        const bsAlert = new bootstrap.Alert(alertDiv);
        bsAlert.close();
    }, 5000);
}

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${message}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', function() {
        document.body.removeChild(toast);
    });
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = function() {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 导出功能
function exportData(format) {
    const selectedItems = getSelectedItems();
    if (selectedItems.length === 0) {
        showAlert('请先选择要导出的项目', 'warning');
        return;
    }
    
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/admin/export/${format}`;
    
    selectedItems.forEach(function(itemId) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'selected_items';
        input.value = itemId;
        form.appendChild(input);
    });
    
    document.body.appendChild(form);
    form.submit();
}

// 导入功能
function importData() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.csv,.xlsx,.json';
    input.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            uploadImportFile(file);
        }
    });
    input.click();
}

function uploadImportFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    fetch('/admin/import', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(`成功导入 ${data.count} 条记录`, 'success');
            setTimeout(() => location.reload(), 2000);
        } else {
            showAlert(data.message || '导入失败', 'danger');
        }
    })
    .catch(error => {
        console.error('导入失败:', error);
        showAlert('导入失败，请重试', 'danger');
    });
}

